import { getUserByIdDetail, getUserProfile, login } from '@/api/user'
import { removeToken } from '@/utils/auth'
import { Message } from 'element-ui'

export default {
  // 放入核心的配置项
  namespaced: true, // 子模块开启命名空间
  state: {
    token: localStorage.getItem('token') || '',
    userInfo: {}
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    delToken(state) {
      state.token = ''
      removeToken()
    },
    updateUserInfo(state, info) {
      state.userInfo = info
    },
    delUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async initToken(context, formData) {
      const res = await login(formData)
      if (res.code !== 10000) return Message.error(res.message)
      Message.success(res.message)
      context.commit('updateToken', res.data)
    },
    async getUserInfo(context) {
      try {
        const res = await getUserProfile()
        const info = await getUserByIdDetail(res.data.userId)
        console.log(info)
        context.commit('updateUserInfo', { ...res.data, ...info.data })
        return res.data.roles.menus
      } catch (error) {
        console.log(error)
      }
    },
    logout(context) {
      context.commit('delToken')
      context.commit('delUserInfo')
    }
  }
}

